package com.yksj.healthtalk.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartControlClient;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R.id;
import com.yksj.healthtalk.ui.app.AppUpdateManager;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.DoctorChatActivity;
import com.yksj.healthtalk.ui.dictionary.DictionaryMainActivity;
import com.yksj.healthtalk.ui.doctor.DoctorDepartmentsListActivity;
import com.yksj.healthtalk.ui.doctorstation.DoctorHomeMainActivity;
import com.yksj.healthtalk.ui.doctorstation.active.ActivesListActivity;
import com.yksj.healthtalk.ui.friend.FriendSearchAboutZxingActivity;
import com.yksj.healthtalk.ui.home.MyHomeMainActivity;
import com.yksj.healthtalk.ui.interestwall.InterestMainActivity;
import com.yksj.healthtalk.ui.login.DoctorRegisteUI;
import com.yksj.healthtalk.ui.news.MainNewsActivity;
import com.yksj.healthtalk.ui.salon.SalonMainUIActivity;
import com.yksj.healthtalk.ui.server.ServerCenterFreeShopReadActivity;
import com.yksj.healthtalk.ui.server.ServerCenterMainUI;
import com.yksj.healthtalk.ui.setting.SettingAboutHealthActivity;
import com.yksj.healthtalk.ui.setting.SettingQrCodeActivity;
import com.yksj.healthtalk.ui.views.CirclePageIndicator;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.ViewFinder;
import com.yksj.healthtalk.utils.ViewUtils;

public class MainTabUI extends BaseFragmentActivity implements OnClickListener {
	
	private ViewPager mViewPager;
	private final DisplayMetrics metrics = new DisplayMetrics();
	private TabsPagerAdapter adapter;
	
	
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main_tab_ui_layout);
		HTalkApplication.onHandleCrashedLogin(bundle,this);
		initUI();
		onHandleEnterShop(bundle);
		onUpdateApp();
	}
	
	/**
	 * 检测更新
	 */
	private void onUpdateApp(){
		if(!getIntent().hasExtra("isFromLogin")){
			new AppUpdateManager(this,false).checkeUpdate();
		}
	}
	
	/**
	 * 进入到指定商户
	 */
	private void onHandleEnterShop(Bundle bundle){
		if(bundle == null && getIntent().hasExtra("merchantId")){
			final String MERCHANT_ID = getIntent().getStringExtra("merchantId");
			HttpRestClient.doHttpServerCneterBg(
					String.valueOf(metrics.widthPixels), 
					String.valueOf(metrics.heightPixels), 
					SmartFoxClient.getLoginUserId(),
					MERCHANT_ID,
					new JsonsfHttpResponseHandler(){
				@Override
				public void onSuccess(int statusCode,JSONObject response) {
					super.onSuccess(statusCode, response);
					String str = response.getString("VALID_FLAG");
					if (!"2".equals(str)) {// 不可以进入
						Intent intent=new Intent(MainTabUI.this,ServerCenterMainUI.class);
						Bundle bundle=new Bundle();
						bundle.putString("content",response.toString());
						bundle.putString("MERCHANT_ID",MERCHANT_ID);
						intent.putExtras(bundle);
						startActivity(intent);
					}
				}
			});
		}
	}
	
	
	private void initUI(){
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		mViewPager = (ViewPager)findViewById(id.pager);
		CirclePageIndicator indicator = (CirclePageIndicator)findViewById(id.indicator);
		adapter = new TabsPagerAdapter();
		mViewPager.setAdapter(adapter);
		indicator.setViewPager(mViewPager);
		
		findViewById(id.logo).setOnClickListener(this);
		EditText searchEditText = (EditText) findViewById(id.search_input);
		searchEditText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				SearchDialogFragment.onShowDialog(getSupportFragmentManager());
			}
		});
		adapter.onChange();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		queryDataCount();
	}
	
	@Override
	public void onBackPressed() {
		//回到桌面
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		Intent intent =new Intent(this,CoreService.class);
		intent.setAction(CoreService.ACTION_FRAME_VIEW_VISIABLE);
		intent.putExtra("className",this.getClass().getName());
		startService(intent);
	}
	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case id.symptoms_of_visits://免费速答
			intent = new Intent(this,DoctorChatActivity.class);
			startActivity(intent);
			break;
		case id.professional_doctor://医生诊所
			intent = new Intent(this, DoctorDepartmentsListActivity.class);
			startActivity(intent);
			break;
		case id.drug_buy://药品购买
			intent = new Intent(this,ServerCenterFreeShopReadActivity.class);
			intent.putExtra("id", "1");
			intent.putExtra("title","药品购买");
			startActivity(intent);
			break;
		case id.salon_talk://话题交流
			intent = new Intent(this, SalonMainUIActivity.class);
			startActivity(intent);
			break;
		case id.personal_publishing://兴趣
			intent = new Intent(this, InterestMainActivity.class);
			startActivity(intent);
			break;
		case id.ac_patients://病友社区
			intent = new Intent(this, CommunityActivity.class);
			intent.putExtra("id",0);
			startActivity(intent);
			break;
		case id.health_news://健康要闻
			intent = new Intent(this,MainNewsActivity.class);
			startActivity(intent);
			break;
		case id.doctor_register://医生注册 OR 我的诊所
			if(SmartFoxClient.getLoginUserInfo().isDoctor()){
				intent = new Intent(this, DoctorHomeMainActivity.class);
			}else{
				intent = new Intent(this, DoctorRegisteUI.class);
			}
			startActivity(intent);
			break;
		case id.my_home://我的壹健康
			intent = new Intent(this, MyHomeMainActivity.class);
			startActivity(intent);
			break;
		case id.health_services://体检保健
			intent=new Intent(this,ServerCenterListActivity.class);
			intent.putExtra("type",3);
			startActivity(intent);
			break;
		case id.hospital_organization://医院中心
			intent=new Intent(this,ServerCenterListActivity.class);
			intent.putExtra("type",2);
			startActivity(intent);
			break;
		case id.mian_businesses://医药展会
			intent=new Intent(this,ServerCenterListActivity.class);
			intent.putExtra("type",5);
			startActivity(intent);
			break;
		case id.mian_industry://行业协会
			intent=new Intent(this,ServerCenterListActivity.class);
			intent.putExtra("type",7);
			startActivity(intent);
			break;
		case id.setting://设置
			intent = new Intent(this, FragmentContentActivity.class);
			intent.putExtra("type", 0);
			startActivity(intent);
			break;
		case id.logo://加入消息界面
			intent = new Intent(this, SettingAboutHealthActivity.class);
			startActivity(intent);
			break;
		case id.seach_qr://扫一扫
			intent = new Intent();
			intent.setClass(this, FriendSearchAboutZxingActivity.class);
			intent.putExtra("type","3");// 0-社交场  1-医生馆 2 商户
			startActivity(intent);
			break;
		case id.qr_code://壹健康二维码
			intent = new Intent(this,SettingQrCodeActivity.class);
			intent.putExtra("type", 2);
			intent.putExtra("title", "壹健康的二维码");
			startActivity(intent);
			break;
		case id.activ_join://活动参与
			intent = new Intent(this,ActivesListActivity.class);
			startActivity(intent);
			break;
		case id.medical_knowledge://医学百科
			 intent = new Intent(this,DictionaryMainActivity.class);
			 startActivity(intent);
			break;
		}
	}
	
	//请求新闻 兴趣墙的未读消息
	private void queryDataCount(){
		HttpRestClient.doHttpMyZoneCount("20",SmartFoxClient.getLoginUserId(),SharePreUtils.fatchNewsReadedLastId(),SharePreUtils.fatchInterestWallId(),new JsonsfHttpResponseHandler(){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);//新闻：80
				try{
					//新闻
					if(response.getInteger("80")==0){
						ViewUtils.setGone(adapter.newsReadNumber,true);
					}else{
						ViewUtils.setGone(adapter.newsReadNumber,false);
						adapter.newsReadNumber.setText(meSageCount( response.getIntValue("80")));
					}
					
					//发布
					if(response.getInteger("200")==0){
						ViewUtils.setGone(adapter.picReadNumber,true);
					}else{
						ViewUtils.setGone(adapter.picReadNumber,false);
						adapter.picReadNumber.setText(meSageCount( response.getIntValue("200")));
					}
					
					//我的壹健康
					if(response.getIntValue("30")==0 && response.getIntValue("40")==0 && response.getIntValue("10")==0){
						ViewUtils.setGone(adapter.myReadNumber,true);
					}else{
						ViewUtils.setGone(adapter.myReadNumber,false);
						adapter.myReadNumber.setText(meSageCount(response.getIntValue("30")+ response.getIntValue("40")+response.getIntValue("10")));
					}
					//我的诊所
					if(adapter.docReadNumber!=null){
					if(response.getInteger("330")==0){
						ViewUtils.setGone(adapter.docReadNumber,true);
					}else{
						ViewUtils.setGone(adapter.docReadNumber,false);
						adapter.docReadNumber.setText(meSageCount( response.getIntValue("330")));
					}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}
	//更新未读消息条数界面
	private String meSageCount(int count){
		String readCount;
		if(count!=0){
			readCount=count >100 ? "99+":String.valueOf(count);
		}else{
			readCount="0";
		}
		return readCount;
	}
	
	private class TabsPagerAdapter extends PagerAdapter{
		final List<View> views = new ArrayList<View>();
		public TextView newsReadNumber;//新闻未读消息
		public TextView picReadNumber;
		public TextView myReadNumber;
		private LayoutInflater layoutInflater;
		private TextView docReadNumber;
		public TabsPagerAdapter() {
			layoutInflater = LayoutInflater.from(MainTabUI.this);
			onChange();
		}
		
		public void onChange(){
			views.clear();
			if(SmartFoxClient.getLoginUserInfo().isDoctor()){//医生
				View v1 = layoutInflater.inflate(R.layout.main_table_doctor_ui_fragment_one,null);
					ViewFinder finder=new ViewFinder(v1);
					finder.onClick(id.professional_doctor, MainTabUI.this);
					finder.onClick(id.ac_patients, MainTabUI.this);
					finder.onClick(id.drug_buy, MainTabUI.this);
					finder.onClick(id.health_news, MainTabUI.this);
					finder.onClick(id.doctor_register, MainTabUI.this);
					finder.onClick(id.my_home, MainTabUI.this);
					newsReadNumber=finder.textView(id.news_number_text);
					picReadNumber=finder.textView(id.picReadNumber);
					myReadNumber=finder.textView(id.my_home_number_text);
					docReadNumber=finder.textView(R.id.docReadNumber);
				View v2 = layoutInflater.inflate(R.layout.main_table_doctor_ui_fragment_two,null);
					ViewFinder finder2=new ViewFinder(v2);
					finder2.onClick(id.hospital_organization, MainTabUI.this);
					finder2.onClick(id.health_services, MainTabUI.this);
					finder2.onClick(id.mian_businesses, MainTabUI.this);
					finder2.onClick(id.activ_join, MainTabUI.this);
					finder2.onClick(id.setting, MainTabUI.this);
					
				views.add(v1);
				views.add(v2);
			}else{//患者
				View v1 = layoutInflater.inflate(R.layout.main_table_patient_ui_fragment_one,null);
				ViewFinder finder=new ViewFinder(v1);
				
					finder.onClick(id.symptoms_of_visits, MainTabUI.this);
					finder.onClick(id.professional_doctor, MainTabUI.this);
					finder.onClick(id.drug_buy, MainTabUI.this);
					finder.onClick(id.ac_patients, MainTabUI.this);
					finder.onClick(id.health_news, MainTabUI.this);
					finder.onClick(id.medical_knowledge, MainTabUI.this);
					finder.onClick(id.my_home, MainTabUI.this);
					finder.onClick(id.my_home_number_text, MainTabUI.this);
					picReadNumber=finder.textView(id.picReadNumber);
					myReadNumber=finder.textView(id.my_home_number_text);
					newsReadNumber=finder.textView(id.news_number_text);
				View v2 = layoutInflater.inflate(R.layout.main_table_patient_ui_fragment_two,null);
				ViewFinder finder2=new ViewFinder(v2);
					finder2.onClick(id.hospital_organization, MainTabUI.this);
					finder2.onClick(id.health_services, MainTabUI.this);
					finder2.onClick(id.mian_businesses, MainTabUI.this);
					finder2.onClick(id.activ_join, MainTabUI.this);
					finder2.onClick(id.setting, MainTabUI.this);
					finder2.onClick(id.doctor_register, MainTabUI.this);
					
				views.add(v1);
				views.add(v2);
			}
			notifyDataSetChanged();
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}
		
		@Override
		public int getCount() {
			return views.size();
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View item = views.get(position);
			container.addView(item);
			return item;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View)object);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}
	}
	
}
